package cn.lili.modules.grab.dingdong.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringEscapeUtils;
import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @description: RSA加解密算法工具类
 * @author: zlb
 * @create: 2021-04-26 11:31
 **/
public class RSAUtil {

    private static RSAPublicKey rsaPublicKey;
    private static RSAPrivateKey rsaPrivateKey;

    static {
        // 1、初始化密钥
        KeyPairGenerator keyPairGenerator;
        try {
            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(512);// 64的整倍数
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
            rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
            //System.out.println("Public Key : " + Base64.getEncoder().encodeToString(rsaPublicKey.getEncoded()));
            //System.out.println("Private Key : " + Base64.getEncoder().encodeToString(rsaPrivateKey.getEncoded()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    /**
     * 公钥加密
     * @Date 2021/4/26 11:41
     * @param content 内容
     * @param key 密钥key(公钥)
     * @return
     **/
    public static String pubEncrypt(String content,String key) throws Exception {
       // X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded()); //默认初始化的公钥
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(key));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] result = cipher.doFinal(Base64.getDecoder().decode(content));
        System.out.println("公钥加密  --加密: " + new String(Base64.getEncoder().encode(result)));
        return Base64.getEncoder().encodeToString(result);
    }

    /**
     * 私钥解密
     * @Date 2021/4/26 11:41
     * @param content 内容
     * @param key 密钥key(私钥)
     * @return
     **/
    public static String privateDecrypt(String content,String key) throws Exception {
       // PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded()); //默认初始化的私钥
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(Base64.getDecoder().decode(content));
        System.out.println("私钥解密  --解密: " + new String(result));
        return  new String(result);
    }

    /**
     * 私钥加密
     * @Date 2021/4/26 11:41
     * @param content 内容
     * @param key 密钥key(私钥)
     * @return
     **/
    public static String privateEncrypt(String content,String key) throws Exception {
       // PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded()); //默认初始化的私钥
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(Base64.getDecoder().decode(content));
        System.out.println("私钥加密    --加密 : " + new String(Base64.getEncoder().encode(result)));
        return Base64.getEncoder().encodeToString(result);
    }

    /**
     * 公钥解密
     * @Date 2021/4/26 11:46
     * @param content 内容
     * @param key 密钥key(公钥)
     * @return
     **/
    public static String pubDecrypt(String content,String key) throws Exception {
       // X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded()); //默认初始化的公钥
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(key));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        byte[] result = cipher.doFinal(Base64.getDecoder().decode(content));
        System.out.println("公钥解密   --解密: " + new String(result));

        return Base64.getEncoder().encodeToString(result);
    }

    public static void main(String[] args) throws Exception {
        //request

        JSONObject obj = new JSONObject();
        obj.put("app_key","58a5c84f-39a5-9f26-cb30-14a403a11a06");
        obj.put("time",Long.valueOf(String.valueOf("1614666916805")));

        JSONObject content = new JSONObject();
        JSONObject data = new JSONObject();
        data.put("goods_id","0");
        data.put("cate_id","0");
        data.put("goods_name","");
        data.put("sort","time");
        data.put("sort_type","desc");
        data.put("page_size","15");
        data.put("page",1);
        data.put("device","6");

        JSONObject base = new JSONObject();
        base.put("equipment","");
        base.put("time",Long.valueOf("1614666916805"));
        base.put("source","99");
        base.put("version","v3.1.2");
        base.put("token","ERGK6BEE347A4F49F545GH2BEB5206C7");

        content.put("data",data);
        content.put("base",base);

        String requestLock = AESUtil.initkey();
        System.out.println("加密并Base64后的lock=="+requestLock);
        String requestEncryptedContent = AESUtil.encrypt("\""+StringEscapeUtils.escapeJava(content.toJSONString())+"\"",requestLock);
        System.out.println("content=====\""+StringEscapeUtils.escapeJava(content.toJSONString())+"\"");

        String requestEncryptedLock = pubEncrypt(requestLock,"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDbXV+2TIBIaRDopdtdWoU9MD7rTqZ8toEw9dYWgNQ+fd22IKbXbaQpQVMQwdQ56DxtSyOvlBmBupXYPc+48fl0/1SGEYf9RShgUE4NrsYvsqEAd3Y1r/HoIltHwjgimsGn8zcXuH6daUl+WcwPjGRPZ+oUPcd8zXnCRH+Gf26RrwIDAQAB");
        obj.put("lock",requestEncryptedLock);
        obj.put("content",requestEncryptedContent);

        System.out.println(obj.toJSONString());
        //*************************************//
       // response
        // 接收响应
        String response = HttpClientUtil.post("http://tintegral.7dingdong.com/api/api_goods/goodsList", obj.toJSONString());
        String result = StringEscapeUtils.unescapeJava(response);
        System.out.println("返回结果==="+result);
        JSONObject resJson = JSON.parseObject(result);
        String responseEncryptedLock = resJson.get("lock").toString();
        String responseEncryptedContent = resJson.get("content").toString();
        String resonpseLock = pubDecrypt(responseEncryptedLock,"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDbXV+2TIBIaRDopdtdWoU9MD7rTqZ8toEw9dYWgNQ+fd22IKbXbaQpQVMQwdQ56DxtSyOvlBmBupXYPc+48fl0/1SGEYf9RShgUE4NrsYvsqEAd3Y1r/HoIltHwjgimsGn8zcXuH6daUl+WcwPjGRPZ+oUPcd8zXnCRH+Gf26RrwIDAQAB");
        String responseContent = AESUtil.decrypt(responseEncryptedContent,resonpseLock);
        JSONObject fullData = new JSONObject();
        fullData.put("status",resJson.get("status"));
        fullData.put("msg",resJson.get("msg"));
        fullData.put("content",JSON.parseArray(responseContent));

        System.out.println(fullData);



    }

}